package com.azkj.album.view.activity;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.azkj.album.MyApplication;
import com.azkj.album.R;
import com.azkj.album.dto.AddOrderBean;
import com.azkj.album.dto.MessageEvent;
import com.azkj.album.dto.MessageType;
import com.azkj.album.dto.UpdateBean;
import com.azkj.album.dto.UploadBean;
import com.azkj.album.network.Constants;
import com.azkj.album.network.NetworkMaster;
import com.azkj.album.network.callback.ServiceCallback;
import com.azkj.album.network.networkframe.bean.BaseResp;
import com.azkj.album.network.networkframe.net.exception.ApiException;
import com.azkj.album.network.utils.ToastUtils;
import com.azkj.album.presenter.UpLoadPresenter;
import com.azkj.album.presenter.UpdatePresenter;
import com.azkj.album.utils.PermissionsUtils;
import com.azkj.album.view.base.BaseActivity;
import com.azkj.album.view.fragment.GalleryFragment;
import com.azkj.album.view.fragment.MainFragment;
import com.azkj.album.view.fragment.RecoveryFragment;
import com.azkj.album.view.fragment.UserFragment;
import com.azkj.album.view.iview.IUpdateView;
import com.azkj.album.view.iview.IUploadView;
import com.azkj.album.view.widgets.TabView;
import com.azkj.album.view.widgets.dialog.DialogHelper;
import com.azkj.album.view.widgets.dialog.UpdateAppDialog;
import com.azkj.album.view.widgets.dialog.VipNoticeDialog;
import com.umeng.analytics.MobclickAgent;
import com.vachel.editor.PictureEditActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class HomeActivity extends BaseActivity implements TabView.OnTabSelectedListener, IUpdateView, IUploadView {
    public static final String PUSH_MESSAGE = "push_message";
    @BindView(R.id.tab_widget)
    TabView mTabWidget;

    private FragmentManager mFragmentManager;
    private Fragment mContentFragment;
    private int mIndex = 0;
    private List<Fragment> fragments = new ArrayList<>();

    private UpdatePresenter updatePresenter;
    private UpdateAppDialog.Builder mUpdateBuilder;

    private String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
    private PermissionsUtils permissionsUtils = new PermissionsUtils();

    private static final int REQUEST_CAMERA = 100;
    private static final int REQUEST_ALBUM = 101;
    private static final int REQUEST_EDIT = 102;
    private static final String TAG = HomeActivity.class.getSimpleName();


    private UpLoadPresenter upLoadPresenter;

    private int mUploadType = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().post(new MessageEvent(MessageType.TYPE_START_HOME_ACTIVITY));
    }


    private void initTab() {
        getMyTabWidgetHeight();
        mTabWidget.removeAllViews();
        mTabWidget.init(this);
        mTabWidget.setOnTabSelectedListener(this);

        fragments.add(new MainFragment());
        fragments.add(new GalleryFragment());
        fragments.add(new RecoveryFragment());
        fragments.add(new UserFragment());


        mFragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = mFragmentManager.beginTransaction();

        mContentFragment = fragments.get(0);
        mTabWidget.removeAllViews();
        mTabWidget.init(this);
        transaction.add(R.id.fl_home_content, mContentFragment);
        transaction.commitAllowingStateLoss();
        mTabWidget.setTabsDisplay(mIndex);

    }

    private void switchFragment(int index) {
        if (mContentFragment != fragments.get(index)) {
            FragmentTransaction transaction = mFragmentManager.beginTransaction().setCustomAnimations(R.anim.home_fade_in, R.anim.home_fade_out);
            if (!fragments.get(index).isAdded()) {    // 先判断是否被add过
                transaction.hide(mContentFragment).add(R.id.fl_home_content, fragments.get(index), index + "").commitAllowingStateLoss(); // 隐藏当前的fragment，add下一个到Activity中
            } else {
                transaction.hide(mContentFragment).show(fragments.get(index)).commitAllowingStateLoss(); // 隐藏当前的fragment，显示下一个
            }
            mContentFragment = fragments.get(index);
        }
    }

    @Override
    public void onTabSelected(int index) {
        if (mIndex == index) return;
        mIndex = index;
        switchFragment(mIndex);
        mTabWidget.setTabsDisplay(mIndex);
        EventBus.getDefault().post(new MessageEvent(MessageType.TYPE_ON_HOME_TAB_SELECTED, mIndex));
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_home;
    }


    @Override
    public void initView() {
        initTab();
        handleMessage(getIntent());
        mTabWidget.getCenterBtn().setOnClickListener(v -> {

            NetworkMaster.getInstance().getCommonService().getCanAddOrder(new ServiceCallback<BaseResp<AddOrderBean>>() {
                @Override
                public void onSuccess(BaseResp<AddOrderBean> jsonObj) {
                    DialogHelper.hideDialog();
                    if (jsonObj.getCode() == 1) {
                        if ("0".equals(jsonObj.getData().getCan())) {
                            new VipNoticeDialog.Builder(HomeActivity.this)
                                    .setDesc(jsonObj.getMsg()).setOnClickListener((dialog, confirm) -> {
                                        dialog.dismiss();
                                        if (confirm) {
                                            startActivity(new Intent(HomeActivity.this, MemberActivity.class));
                                        }
                                    }).show();

                        } else {
                            Intent intent = new Intent(HomeActivity.this, NewPhotoActivity.class);
                            startActivity(intent);
                        }


                    } else {
                        ToastUtils.showCenterToast(jsonObj.getMsg());
                    }
                }

                @Override
                public void onError(ApiException apiException) {
                    ToastUtils.showCenterToast(apiException.errorInfo.error);
                }
            });


        });
    }

    private void getMyTabWidgetHeight() {
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        mTabWidget.measure(w, h);
    }

    @Override
    public void initData() {

    }

    @Override
    protected void initPresenter() {
        updatePresenter = new UpdatePresenter(this);
        upLoadPresenter = new UpLoadPresenter(this);
    }

    private long firstTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (System.currentTimeMillis() - firstTime > 2000) {
                ToastUtils.showToast(HomeActivity.this, "再按一次退出应用");
                firstTime = System.currentTimeMillis();
            } else {
                MobclickAgent.onKillProcess(MyApplication.getApplication());
                finish();

            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Subscribe
    public void onMessage(MessageEvent messageEvent) {
        super.onMessage(messageEvent);
        switch (messageEvent.getType()) {
            case MessageType.TYPE_START_LOGIN_ACTIVITY:
            case MessageType.TYPE_ON_LOGIN_START:
                finish();
                break;
            case MessageType.TYPE_ON_USER_UPDATE_CLICKED:
                updatePresenter.checkVersion(true);
                break;
            case MessageType.TYPE_ON_USER_SHARE_CLICKED:
                shareWeb(false, Constants.WEB_PAGE_SHARE, getString(R.string.app_name), "快捷生成销售单，点击链接即可下载！");
                break;

            case MessageType.TYPE_NOTIFY_CHANGE_TAB:
                mTabWidget.changeTab(messageEvent.getPosition());
                break;

            case MessageType.TYPE_ON_FRAGMENT_UPLOAD_MAP_CLICK:
                mUploadType = 0;
                onPhoto();
                break;
            case MessageType.TYPE_ON_FEED_UPLOAD_CLICK:
                mUploadType = 1;
                onPhoto();
                break;

        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        permissionsUtils.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
        // 获取到Activity下的Fragment
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        if (fragments == null || fragments.size() == 0) {
            return;
        }
        // 查找在Fragment中onRequestPermissionsResult方法并调用
        for (Fragment fragment : fragments) {
            if (fragment != null) {
                // 这里就会调用我们Fragment中的onRequestPermissionsResult方法
                fragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
            }
        }
    }

    @Override
    public void showUpdateDialog(UpdateBean updateBean) {
        if (mUpdateBuilder == null) {
            mUpdateBuilder = new UpdateAppDialog.Builder(this);
        }
        mUpdateBuilder.setUpdateBean(updateBean).setUpdateListener(() -> permissionsUtils.checkPermissions(HomeActivity.this, permissions, new PermissionsUtils.IPermissionsResult() {
            @Override
            public void passPermissions() {
                mUpdateBuilder.download();
            }

            @Override
            public void forbidPermissions() {

            }
        })).show();

    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        handleMessage(intent);
    }


    private void handleMessage(Intent intent) {
        if (intent == null || !intent.hasExtra(PUSH_MESSAGE)) return;
        try {


            JSONObject jsonObject = JSON.parseObject(intent.getStringExtra(PUSH_MESSAGE));
//            //系统消息
//            if ("1".equals(jsonObject.getString("type"))) {
//                Intent intent1 = new Intent(this, MsgInfoActivity.class);
//                intent1.putExtra("mMsgId", jsonObject.getString("oid"));
//                startActivity(intent1);
//                //直播
//            } else if ("10".equals(jsonObject.getString("type"))) {
//                Intent intent2 = new Intent(this, LiveActivity.class);
//                intent2.putExtra("mPageType", 0);
//                intent2.putExtra("mLiveId", Integer.parseInt(jsonObject.getString("oid")));
//                startActivity(intent2);
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void onPhoto() {
        permissionsUtils.checkPermissions(this, permissions, new PermissionsUtils.IPermissionsResult() {
            @Override
            public void passPermissions() {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, REQUEST_ALBUM);
            }

            @Override
            public void forbidPermissions() {
                ToastUtils.showCenterToast("请打开存储权限");
            }
        });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG, "requestCode:" + requestCode + "---resultCode:" + resultCode);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_ALBUM) {     //相册返回
                Uri uri = data.getData();
                Log.d(TAG, "album:" + uri.toString());
                Intent editIntent = new Intent(this, PictureEditActivity.class);
                editIntent.putExtra(PictureEditActivity.EXTRA_IMAGE_URI, uri);
                startActivityForResult(editIntent, REQUEST_EDIT);
            } else if (requestCode == REQUEST_EDIT) {     //编辑返回
                String path = data.getStringExtra(PictureEditActivity.RESULT_IMAGE_SAVE_PATH);
                Log.d(TAG, "album:" + path);
                new Handler().postDelayed(() -> upLoadPresenter.uploadPath(path), 500);
            }
        }
    }


    @Override
    public void uploadSuccess(ArrayList<String> data) {

    }

    @Override
    public void uploadPathSuccess(UploadBean data) {
        Log.d(TAG, "uploadPathSuccess:" + data.getFullurl());
        if (mUploadType == 0) {
            EventBus.getDefault().post(new MessageEvent(MessageType.TYPE_ON_FRAGMENT_UPLOAD_MAP_SUCCESS, data.getFullurl(), 1));
        } else if (mUploadType == 1) {
            EventBus.getDefault().post(new MessageEvent(MessageType.TYPE_ON_FEED_UPLOAD_SUCCESS, data.getFullurl()));
        }
    }

    @Override
    public void uploadFail(String msg) {
        ToastUtils.showCenterLongToast(msg);
    }
}
